package com.example.shopingcenter.Fragment;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.shopingcenter.DateBase.ShoppingDbHelper;
import com.example.shopingcenter.MyApplication;
import com.example.shopingcenter.R;
import com.example.shopingcenter.activity.ShoppingCartActivity;
import com.example.shopingcenter.activity.ShoppingDetalsActivity;
import com.example.shopingcenter.enity.GoodsInfo;
import com.example.shopingcenter.util.ViewPagerAdapter;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.util.Arrays;
import java.util.List;


public class HomeFragment extends Fragment implements View.OnClickListener{

    FrameLayout frameLayout;
    private ShoppingDbHelper mdbHelper;
    private TextView tv_count;
    private GridLayout gl_channel;
    private ViewPager2 viewPager;
    private ViewPagerAdapter adapter;
    private LinearLayout indicatorGroup;
    public static List<Integer> imageList;
    private BottomNavigationView bottomNavigationView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
       View view= inflater.inflate(R.layout.fragment_home, container, false);

        TextView  tv_title=view.findViewById(R.id.tv_title);
        bottomNavigationView = view.findViewById(R.id.bottom_navigation);
        viewPager = view.findViewById(R.id.viewPager);
        indicatorGroup =view. findViewById(R.id.indicatorGroup);
        frameLayout=view.findViewById(R.id.linear_container);



        imageList = Arrays.asList(
                R.drawable.apple,
                R.drawable.suanxing3,
                R.drawable.xiaomi,
                R.drawable.oppo,
                R.drawable.vivo,
                R.drawable.huawei

        );


        adapter = new ViewPagerAdapter(getContext(), imageList);
        viewPager.setAdapter(adapter);

        // 自动轮播设置（可选）
        autoScrollViewPager();
        setUpIndicators();


        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);

                updateIndicators(position);

            }
        });



        tv_title.setText("手机商城");
        tv_count = view.findViewById(R.id.tv_count);
        gl_channel =view. findViewById(R.id.gl_channel);


      view.  findViewById(R.id.iv_back).setOnClickListener( this);
      view.  findViewById(R.id.iv_cart).setOnClickListener( this);


        mdbHelper=ShoppingDbHelper.getDbHelper(getContext());
        mdbHelper.openReadLink();
        mdbHelper.openWriteLink();

        showGoods();


       return  view;
    }

    private void setUpIndicators() {
        // 根据图片数量创建指示器
        for (int i = 0; i < imageList.size(); i++) {
            ImageView indicator = new ImageView(getContext());
            indicator.setLayoutParams(new ViewGroup.LayoutParams(30, 15));
            indicator.setPadding(15, 0, 15, 0);
            indicator.setBackgroundResource(R.drawable.indicator_unselected); // 默认未选中状态
            indicatorGroup.addView(indicator);
        }

        // 初始化时选中第一个页面
        updateIndicators(0);
    }

    private void updateIndicators(int selectedPosition) {
        // 更新指示器状态
        for (int i = 0; i < indicatorGroup.getChildCount(); i++) {
            ImageView indicator = (ImageView) indicatorGroup.getChildAt(i);
            if (i == selectedPosition) {
                indicator.setBackgroundResource(R.drawable.indicator_selected); // 选中状态
            } else {
                indicator.setBackgroundResource(R.drawable.indicator_unselected); // 未选中状态
            }
        }
    }

    private void autoScrollViewPager() {
        final Runnable runnable = new Runnable() {
            int currentPage = 0;

            @Override
            public void run() {
                int itemCount = adapter.getItemCount();
                currentPage = (currentPage + 1) % itemCount;
                viewPager.setCurrentItem(currentPage, true);
                viewPager.postDelayed(this, 3000); // 3秒切换一次
            }
        };
        viewPager.postDelayed(runnable, 3000);
    }


    private void showGoods() {
        int screenWidth=getResources().getDisplayMetrics().widthPixels;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(screenWidth/2 , LinearLayout.LayoutParams.WRAP_CONTENT);


        gl_channel.requestLayout();

        List<GoodsInfo> list = mdbHelper.queryAllGoodsInfo();
        for (GoodsInfo info : list) {
            View view = LayoutInflater.from(getContext()).inflate(R.layout.goods_item, null);
            int color = Color.parseColor("#8089E9DD"); // 将16进制颜色字符串转换为int类型
            view.setBackgroundColor(color);
            ImageView iv_img=view.findViewById(R.id.iv_img);
            TextView name=view.findViewById(R.id.tv_name);
            TextView price=view.findViewById(R.id.tv_price);

            Button btn_add=view.findViewById(R.id.btn_add);


            iv_img.setImageURI(Uri.parse(info.picPath));
            name.setText(info.name);
            price.setText(String.valueOf((int) info.price));

            btn_add.setOnClickListener(v->{
                addToCart(info.id,info.name);
            });

            iv_img.setOnClickListener(v->{
                Intent intent=new Intent(getContext(), ShoppingDetalsActivity.class);
                intent.putExtra("goods_id",info.id);
                Log.v("id",String.valueOf(info.id));
                startActivity(intent);
            });



            gl_channel.addView(view, params);


        }

    }

    private void addToCart(int goodsId, String goodsName) {
        mdbHelper.insertCartInfo(goodsId);
        int count=  ++MyApplication.getmApp().goodsCount;
        tv_count.setText(String.valueOf(count));
        Toast.makeText(getContext(), "已添加一部"+goodsName+"到购物车", Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onResume() {
        super.onResume();
        showCartInfoTotal();
    }

    private void showCartInfoTotal() {
        int count=  mdbHelper.countCartInfo();
        MyApplication.getmApp().goodsCount=count;
        tv_count.setText(String.valueOf(count));
    }

    public void onDestroy() {

        super.onDestroy();
//        mdbHelper.closeLink();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_back:
                getActivity().finish();
                break;
            case R.id.iv_cart:

                Intent intent=new Intent(getContext(), ShoppingCartActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);

                break;
        }
    }
}